Telegram Group & Telegram Channel
🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from collections.abc (collections.abc) import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬



@Python_Community_ru



tg-me.com/Python_Community_ru/2626
Create:
Last Update:

🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from collections.abc (collections.abc) import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬



@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2626

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

Can I mute a Telegram group?

In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

Python Community from us


Telegram Python Community
FROM USA